package com.kgc.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kgc.common.Result;
import com.kgc.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hyj
 * @time 2024/4/2 8:55
 * @describe
 */

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null || "".equals(token)) {
            token = request.getParameter("token");
        }

        // 解密
        if (StringUtils.isNotBlank(token)) {
            Claims claims = JwtUtil.parseJwt(token);
            if (claims == null) {
                sendJsonMessage(response, Result.success("10", "登录过期，重新登录"));
                return false;
            }
            String userPhone = (String) claims.get("userPhone");
            request.setAttribute("userPhone", userPhone);
            return true;
        }
        sendJsonMessage(response, Result.success("10", "登录过期，重新登录"));
        return false;
    }

    public static void sendJsonMessage(HttpServletResponse response, Object object) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(objectMapper.writeValueAsString(object));
        response.getWriter().close();
        response.flushBuffer();
    }
}
